<template>
  <div class="container">
    <div class="filter">
      <van-field
        v-model="city"
        is-link
        arrow-direction="down"
        readonly
        label=""
        placeholder="请选择"
        @click="showPicker = true"
        style="width: 50%;margin-right: 10px;"
      />
      <van-field
        v-model="year"
        is-link
        arrow-direction="down"
        readonly
        label=""
        placeholder="请选择"
        @click="showYearPicker = true"
        style="width: 50%;"
      />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker
          title=""
          :columns="cityOptions"
          :columns-field-names="customFieldName"
          @cancel="showPicker = false"
          @confirm="confirmFunction"
        />
      </van-popup>
      <van-popup v-model:show="showYearPicker" round position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="请选择"
          :min-date="new Date(2023, 0, 1)"
          :max-date="new Date()"
          :columns-type="columnsType"
          @cancel="showYearPicker = false"
          @confirm="confirmYear"
        />
      </van-popup>
    </div>    
    <div class="content">
      <div class="top">
        <div class="title">温度统计(℃)</div>
        <div class="tip">数据来源：广东气象局</div>
      </div>
      <div id="lineChart1" style="height: 200px;"></div>
    </div>
    <div class="content">
      <div class="top">
        <div class="title">风力统计(m/s)</div>
        <div class="tip">数据来源：广东气象局</div>
      </div>
      <div id="lineChart2" style="height: 200px;"></div>
    </div>
    <div class="content">
      <div class="top">
        <div class="title">降水量统计(mm)</div>
        <div class="tip">数据来源：广东气象局</div>
      </div>
      <div id="lineChart3" style="height: 200px;"></div>
    </div>
    <div class="tips">说明：以上数据取自各月份统计数据的平均值</div>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick } from 'vue';

  import * as echarts from 'echarts/core';
  import { TooltipComponent, GridComponent, LegendComponent } from 'echarts/components';
  import { LineChart } from 'echarts/charts';
  import { UniversalTransition } from 'echarts/features';
  import { CanvasRenderer } from 'echarts/renderers';
  echarts.use([TooltipComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, UniversalTransition]);

  // 引入api
  import {
    getProvince, //获取市
    weatherStat, //气象统计
  } from "@/bridge-h5/utils/myapi";

  const city = ref("");
  const showPicker = ref(false);
  const customFieldName = {
    text: 'city',
    value: 'city',
  };
  const confirmFunction = ({ selectedOptions }) => {
    city.value = selectedOptions[0].city;
    weatherStatFunction();
    showPicker.value = false;
  };

  const cityOptions = ref([]);
  const getProvinceFunction = () => {
    getProvince().then((res) => {
      if(res.code === 200){
        cityOptions.value = res.data;
        city.value = res.data[0].city;
        weatherStatFunction();
      }
    });
  };

  const year = ref(new Date().format("yyyy"));
  const currentDate = ref([new Date().format("yyyy")]);
  const columnsType = ['year'];
  const showYearPicker = ref(false);
  const confirmYear = (val) => {
    year.value = val.selectedValues[0];
    weatherStatFunction();
    showYearPicker.value = false;
  };
  const xAxisData1 = ref([]);
  const xAxisData2 = ref([]);
  const xAxisData3 = ref([]);
  const seriesData1 = ref([]);
  const seriesData2 = ref([]);
  const seriesData3 = ref([]);
  const weatherStatFunction = () => {
    weatherStat(city.value, year.value).then((res) => {
      if(res.code === 200){
        xAxisData1.value = [];
        seriesData1.value = [];
        xAxisData2.value = [];
        seriesData2.value = [];
        xAxisData3.value = [];
        seriesData3.value = [];
        res.data.temp.forEach((item1) => {  
          // if(item1.month >= "10"){
          //   xAxisData1.value.push(`${item1.month}月`);
          // }else{
          //   xAxisData1.value.push(`${item1.month.replace("0","")}月`);
          // }     
          xAxisData1.value.push(item1.ny);           
          seriesData1.value.push(item1.temperature);
        });
        res.data.wind.forEach((item2) => {          
          // if(item2.month >= "10"){
          //   xAxisData2.value.push(`${item2.month}月`);
          // }else{
          //   xAxisData2.value.push(`${item2.month.replace("0","")}月`);
          // }  
          xAxisData2.value.push(item2.ny);
          seriesData2.value.push(item2.windSpeed);
        });
        res.data.water.forEach((item3) => {      
          // if(item3.month >= "10"){
          //   xAxisData3.value.push(`${item3.month}月`);
          // }else{
          //   xAxisData3.value.push(`${item3.month.replace("0","")}月`);
          // }     
          xAxisData3.value.push(item3.ny);
          seriesData3.value.push(item3.water);
        });
      }
      nextTick(() => {
        initLineChart1();
        initLineChart2();
        initLineChart3();
      });
    });
  };

  const initLineChart1 = () => {    
    let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart1"));
    if(lineChart != null && lineChart != "" && lineChart != undefined){
      lineChart.dispose();
    }
    lineChart = echarts.init(document.getElementById('lineChart1'));

    let option;
    option = {
      tooltip: {
        trigger: 'axis',
        confine: true, //限制在图表区域内
        formatter: function (params) {
          let template = `${params[0].axisValue}<br>`;         
          for(let i = 0; i < params.length; i++){
            let item = params[i];
            template += item.marker + '温度: ' + item.value + '℃' + '<br>'
          }  
          return template  
        },  
      },
      grid: {
        top: '40px',
        left: '40px',
        right: '40px',
        bottom: '28%',
      },
      xAxis: {
        type: 'category',        
        // data: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],
        data: xAxisData1.value,
        name: '月份',
        axisLabel: {
          interval:0, 
          rotate: 60,
        },  
        nameTextStyle: {
          fontWeight: "500",
          fontSize: "10px",
          color: "rgba(0,0,0,0.45)",
        },
      },
      yAxis: {
        type: 'value',
        name: '单位：℃',
      },
      series: [
        {
          data: seriesData1.value,
          type: 'line',   
          color: '#eb50ec'  
        }
      ]
    };
    option && lineChart.setOption(option);
  };
  const initLineChart2 = () => {
    let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart2"));
    if(lineChart != null && lineChart != "" && lineChart != undefined){
      lineChart.dispose();
    }
    lineChart = echarts.init(document.getElementById('lineChart2'));

    let option;
    option = {
      tooltip: {
        trigger: 'axis',
        confine: true, //限制在图表区域内
        formatter: function (params) {
          let template = `${params[0].axisValue}<br>`;         
          for(let i = 0; i < params.length; i++){
            let item = params[i];
            template += item.marker + '风力: ' + item.value + 'm/s' + '<br>'
          }  
          return template  
        },  
      },
      grid: {
        top: '40px',
        left: '40px',
        right: '40px',
        bottom: '28%',
      },
      xAxis: {
        type: 'category',        
        // data: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],
        data: xAxisData2.value,
        name: '月份',
        axisLabel: {
          interval:0, 
          rotate: 60,
        },
        nameTextStyle: {
          fontWeight: "500",
          fontSize: "10px",
          color: "rgba(0,0,0,0.45)",
        },
      },
      yAxis: {
        type: 'value',
        name: '单位：m/s',
      },
      series: [
        {
          data: seriesData2.value,
          type: 'line', 
          color: '#68efa8'   
        }
      ]
    };
    option && lineChart.setOption(option);
  };
  const initLineChart3 = () => {
    let lineChart = echarts.getInstanceByDom(document.getElementById("lineChart3"));
    if(lineChart != null && lineChart != "" && lineChart != undefined){
      lineChart.dispose();
    }
    lineChart = echarts.init(document.getElementById('lineChart3'));

    let option;
    option = {
      tooltip: {
        trigger: 'axis',
        confine: true, //限制在图表区域内
        formatter: function (params) {
          let template = `${params[0].axisValue}<br>`;         
          for(let i = 0; i < params.length; i++){
            let item = params[i];
            template += item.marker + '降水量: ' + item.value + 'mm' + '<br>'
          }  
          return template  
        },  
      },
      grid: {
        top: '40px',
        left: '40px',
        right: '40px',
        bottom: '28%',
      },
      xAxis: {
        type: 'category',        
        // data: ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],
        data: xAxisData3.value,
        name: '月份',
        axisLabel: {
          interval:0, 
          rotate: 60,
        }, 
        nameTextStyle: {
          fontWeight: "500",
          fontSize: "10px",
          color: "rgba(0,0,0,0.45)",
        },
      },
      yAxis: {
        type: 'value',
        name: '单位：mm',
      },
      series: [
        {
          data: seriesData3.value,
          type: 'line',    
          color: '#f0eb77' 
        }
      ]
    };
    option && lineChart.setOption(option);
  };

  onMounted(() => {
    getProvinceFunction();
  });

</script>

<style lang="scss" scoped>
  .container{
    padding-bottom: 16px;
    margin: 0 16px;
    .filter{
      display: flex;
      margin: 20px 0px 16px 0px;
    }    
    .tips{
      text-align: center;
      font-size: 14px;  
      color: #595959;    
      margin-bottom: 10px;
    }
    .content{
      background: #FFFFFF;
      box-shadow: 0px 4px 8px 2px rgba(0,0,0,0.08);
      border-radius: 8px;
      margin-bottom: 16px;
      .top{
        background: rgba(22,93,255,0.05);
        box-shadow: 0px 1px 0px 0px rgba(0,0,0,0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title{
          font-size: 16px;
          font-weight: bold;
          color: rgba(0,0,0,0.85);       
          padding: 8px 0px 8px 16px;        
        }
        .tip{
          font-weight: 400;
          font-size: 14px;
          color: #8C8C8C;
          padding-right: 16px;
        }
      }      
    }
  }
</style>